package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.model.dao.HProductMapper;
import com.flea.hclv.model.dao.HVideoTrainingMapper;
import com.flea.hclv.model.entity.HProduct;
import com.flea.hclv.model.entity.HResourceRelation;
import com.flea.hclv.model.entity.HVideoTraining;
import com.flea.hclv.model.entity.vo.HVideoVo;
import com.flea.hclv.service.HResourceRelationService;
import com.flea.hclv.service.HVideoTrainingService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.dao.OrgUserMapper;
import com.flea.system.entity.OrgUser;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @program: project
 * @description: 视频培训
 * @author: shiliqiang
 * @create: 2018-11-04 20:14
 * @version: 1.0
 */
@Service
public class HVideoTrainingServiceImpl implements HVideoTrainingService {

    @Autowired
    private HVideoTrainingMapper hVideoTrainingMapper;
    @Autowired
    private HProductMapper hProductMapper;
    @Autowired
    private OrgUserMapper orgUserMapper;
    @Autowired
    private HResourceRelationService hResourceRelationService;


    @Override
    public ServerResponse<Map<String, Object>> selectHomeDataTwo() {
        //最新的10条视频
        List<HVideoTraining> videos =  hVideoTrainingMapper.selectByTopTen();
        Map<String,Object> map = Maps.newHashMap();
        map.put("videos",videos);
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse<Map<String, Object>> selectHomeData() {
        //最新的10条视频
        List<HVideoTraining> videos =  hVideoTrainingMapper.selectByTopTen();

        //最新的10个产品
        List<HProduct> products = hProductMapper.selectTopTen();
        for (HProduct product : products){
            HResourceRelation image = hResourceRelationService.findFilePathByUuid(product.getId()).get(0);
            if (image!=null){
                product.setImageId(image.getResouceId());
                product.setImagePath(image.getPath());
            }
        }
        Map<String,Object> map = Maps.newHashMap();
        map.put("videos",videos);
        map.put("products",products);
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse<FleaPage<HVideoTraining>> selectByProductId(String productId, int curPage, int pageSize) {
        RowBounds rowBounds = new RowBounds(curPage,pageSize);
        List<HVideoTraining> list = hVideoTrainingMapper.selectProductId(productId,rowBounds);
        FleaPage<HVideoTraining> fleaPage = new FleaPage<>(list);
        return ServerResponse.createBySuccess(fleaPage);
    }

    @Override
    public ServerResponse<String> deleteByIds(List<String> idList) {
        int row = hVideoTrainingMapper.deleteByIds(idList);
        if (row>0){
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    @Override
    public ServerResponse<FleaPage<HVideoVo>> selectByDeptId(String userId, int curPage, int pageSize, String model,String deptId) {
        String productName=null;
        String videoName=null;
        if (model!=null){
            HVideoVo videoVo = JSON.parseObject(model,HVideoVo.class);
            productName = videoVo.getProductName();
            videoName = videoVo.getVideoName();
        }
//        OrgDept dept = FleaOrgUtils.getCurrentUserDept(userId);
//        if (dept==null){
//            return ServerResponse.createByErrorMessage("没有找到该用户的部门信息");
//        }
        StringBuilder sb1 = new StringBuilder();
        List<String> productIds;
        if (StringUtils.isNotBlank(productName)){
            sb1.append("%");
            sb1.append(productName);
            sb1.append("%");
            productName = sb1.toString();
            List<HProduct> products = hProductMapper.findLikeName(productName,deptId);
            productIds = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(products)){
                for (HProduct hProduct : products){
                    productIds.add(hProduct.getId());
                }
            }else{
                return ServerResponse.createBySuccess(new FleaPage<HVideoVo>());
            }
        }else {
            productIds=null;
        }

        RowBounds rowBounds = new RowBounds(curPage,pageSize);
        StringBuilder sb2 = new StringBuilder();
        if (StringUtils.isNotBlank(videoName)){
            sb2.append("%");
            sb2.append(videoName);
            sb2.append("%");
            videoName = String.valueOf(sb2);
        }else {
            videoName=null;
        }
        List<HVideoTraining> list = hVideoTrainingMapper.selectByDeptId(deptId,rowBounds,productIds,videoName);
        FleaPage<HVideoTraining> temp = new FleaPage<>(list);
        
       
        List<HVideoVo> voList=null;
        if (CollectionUtils.isNotEmpty(list)){
            voList = this.assembleHVideo(list,deptId);
        }
        FleaPage<HVideoVo> hVideoTrainingFleaPage = new FleaPage<>();
        hVideoTrainingFleaPage.setCurPageData(voList);
        hVideoTrainingFleaPage.setAllDataCount((int)temp.getAllDataCount());
        hVideoTrainingFleaPage.setCurPage(curPage);
        hVideoTrainingFleaPage.setPageSize(pageSize);
        return ServerResponse.createBySuccess(hVideoTrainingFleaPage);
    }
    private List<HVideoVo> assembleHVideo(List<HVideoTraining> list,String deptId){
        List<HVideoVo> hVideoVoList = Lists.newArrayList();
        for (HVideoTraining aList : list) {
            HVideoVo vo = new HVideoVo();
            vo.setId(aList.getId());
            String productId = aList.getProductId();
            HProduct hProduct = hProductMapper.selectByPrimaryKey(productId);
            if (hProduct==null){
                continue;
            }
            vo.setProductId(hProduct.getId());
            vo.setProductName(hProduct.getName());
            vo.setVideoIntroduce(aList.getVideoIntroduce());
            vo.setVideoName(aList.getVideoName());
            vo.setDeptId(deptId);
            vo.setUploadId(aList.getUploadId());
            vo.setVideoPath(aList.getVideoPath());
            vo.setStatus(aList.getStatus());
            String userId = aList.getCreateUser();
            OrgUser user = orgUserMapper.selectByPrimaryKey(userId);
            if (user==null){
                vo.setCreateUser(null);
            }else {
                vo.setCreateUser(user.getUserName());
            }
            vo.setCreateTime(aList.getCreateTime());
            hVideoVoList.add(vo);
        }
        return hVideoVoList;
    }

    @Override
    public ServerResponse<String> update(String userId, HVideoTraining hVideoTraining) {
        if (hVideoTraining==null){
            return ServerResponse.createByErrorMessage("参数传递失败");
        }
        int row = hVideoTrainingMapper.updateByPrimaryKeySelective(hVideoTraining);
        if (row>0){
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }

    @Override
    public ServerResponse<String> save(String userId, String deptId, String model) {
        if (model==null){
            return ServerResponse.createByErrorMessage("没有找到该用户的部门信息");
        }
        JSONArray jsonArray = JSON.parseArray(model);
        if (jsonArray == null || jsonArray.size() == 0){
            return ServerResponse.createByErrorMessage("jsonArray为空");
        }
        List<HVideoTraining> hVideoTrainings = Lists.newArrayList();
        for (int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONObject videos = jsonObject.getJSONObject("videos");
            if (videos.size()==0){
                return ServerResponse.createByErrorMessage("视频不能为空");
            }
            HVideoTraining hVideoTraining = new HVideoTraining();
            hVideoTraining.setId(FleaStringUtils.getGenerateUUID());
            hVideoTraining.setCreateUser(userId);
            hVideoTraining.setModifyUser(userId);
            hVideoTraining.setDeptId(deptId);
            hVideoTraining.setProductId(jsonObject.getString("productId"));

            String videoName = videos.getString("key");
            int index = videoName.lastIndexOf(".");
            videoName = videoName.substring(0,index);

            hVideoTraining.setVideoName(videoName);
            hVideoTraining.setVideoIntroduce(jsonObject.getString("videoIntroduce"));

            hVideoTraining.setUploadId(videos.getString("resouceId"));
            hVideoTraining.setVideoPath(videos.getString("path"));
            hVideoTrainings.add(hVideoTraining);
        }
        if (CollectionUtils.isEmpty(hVideoTrainings)){
            return ServerResponse.createByErrorMessage("list为空");
        }
        for (HVideoTraining hVideoTraining : hVideoTrainings){
            hVideoTraining.setId(FleaStringUtils.getGenerateUUID());
            hVideoTraining.setCreateUser(userId);
            hVideoTraining.setModifyUser(userId);
            hVideoTraining.setDeptId(deptId);
            int row = hVideoTrainingMapper.insertSelective(hVideoTraining);
            if (row<=0){
                return ServerResponse.createByErrorMessage("添加失败");

            }
        }
        return ServerResponse.createBySuccessMessage("添加成功");
    }
}
